import type { requestParams } from '../_util'

import { Random } from 'mockjs'
import { ResultEnum } from '@/utils/enums/http-enum'
import { resultSuccess, resultError, getRequestToken } from '../_util'

const token = Random.string('upper', 32, 32)
const adminToken = 'admin-' + token
const normalToken = 'normal-' + token

const adminInfo = {
  id: '1',
  username: 'admin',
  role: 'ADMIN'
}
const normalInfo = {
  id: '2',
  username: 'normalUser',
  role: 'NORMAL'
}

export default [
  {
    url: '/api/user/login',
    timeout: 100,
    method: 'post',
    response: ({ body }) => {
      const { username } = body
      let resToken = ''
      if (username === 'admin') {
        resToken = adminToken
      } else if (username === 'normal') {
        resToken = normalToken
      } else {
        return resultError({
          message: '用户不存在'
        })
      }
      return resultSuccess({
        result: {
          token: resToken
        }
      })
    },
  },
  {
    url: '/api/user/adminInfo',
    timeout: 100,
    method: 'get',
    response: (request: requestParams) => {
      const token = getRequestToken(request)
      if (!token || (!token.startsWith('admin') && !token.startsWith('normal'))) {
        return resultError({
          code: ResultEnum.TIMEOUT as number,
          message: 'Invalid token',
        })
      }
      let res: any = null
      if (token.startsWith('admin')) {
        res = adminInfo
      }
      if (token.startsWith('normal')) {
        res = normalInfo
      }
      return resultSuccess({
        result: res
      })
    },
  },
]
